package com.str;

public class FindtheIndexoftheFirstOccurrenceinaString0201_28 {
//    public int strStr(String haystack, String needle) {
//        int lenHay = haystack.length(), lenNeed = needle.length();
//
//        for (int i = 0; i <= lenHay - lenNeed; i++) {
//            int start = i;
//            int end = 0;
//            while (end < lenNeed && haystack.charAt(start) == needle.charAt(end)){
//                start++;
//                end++;
//            }
//            if(end == lenNeed){
//                return i;
//            }
//        }
//        return -1;
//    }

    public int strStr(String haystack, String needle) {
        int[] next = new int[needle.length()];
        getNext(needle,next);

        int j = 0;
        for (int i = 0; i < haystack.length(); i++) {
            while (j>0 && haystack.charAt(i) != needle.charAt(j)) j = next[j-1];
            if(haystack.charAt(i) == needle.charAt(j)) j++;
            if (j == needle.length()) return i-j+1;
        }
        return -1;
    }

    //前缀表：找到最长相等前后缀
    public void getNext(String needle, int[] next){
        int j = 0;
        next[0] = 0;
        for (int i = 1; i < needle.length(); i++) {
            while (j>0 && needle.charAt(i) != needle.charAt(j)) j = next[j-1];
            if(needle.charAt(i) == needle.charAt(j)) j++;
            next[i] = j;
        }
    }
}
